package com.hty.filemanager;

import android.content.Intent;
import android.database.Cursor;
import android.os.Environment;
import android.os.Handler;
import android.os.StatFs;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.File;

public class HomeActivity extends AppCompatActivity {
    TextView textView_count_video, textView_count_audio, textView_count_image, textView_count_doc,textView_count_download, textView_count_apk, textView_count_zip, textView_count_bookmark, textView_rom;
    ProgressBar progressBar_rom;
    int count_video=0, count_audio=0, count_image=0, count_download=0, count_doc=0, count_zip=0, count_apk=0, count_bookmark=0;
    long blockCount=0, blockSize=0, availableBlocks=0;
    String rootInfo="";
    Handler handler=null;
    Runnable runnable=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        textView_count_video = findViewById(R.id.textView_count_video);
        textView_count_audio = findViewById(R.id.textView_count_audio);
        textView_count_image = findViewById(R.id.textView_count_image);
        textView_count_doc = findViewById(R.id.textView_count_doc);
        textView_count_download = findViewById(R.id.textView_count_download);
        textView_count_apk = findViewById(R.id.textView_count_apk);
        textView_count_zip = findViewById(R.id.textView_count_zip);
        textView_count_bookmark = findViewById(R.id.textView_count_bookmark);
        textView_rom = findViewById(R.id.textView_rom);
        progressBar_rom = findViewById(R.id.progressBar_rom);

        handler = new Handler();
        runnable = new Runnable() {
            public void run() {
                updateUI();
            }
        };

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        String[] sm = { "搜索", "设置", "更新日志", "关于", "退出" };
        for (int i=0; i<sm.length; i++) {
            menu.add(0, i, i, sm[i]);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int item_id = item.getItemId();
        switch (item_id) {
            case 0:
                startActivity(new Intent(HomeActivity.this, SearchActivity.class));
                break;
            case 1:
                startActivity(new Intent(HomeActivity.this, SettingsActivity.class));
                break;
            case 2:
                new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher).setTitle("更新日志").setMessage("V1.13 (2022-05)\n修复重命名文件没有刷新媒体库问题。\n重命名文件记住位置。\n\nV1.12 (2022-02)\n刷新记住位置。\n排序增加文件夹在前、文件在前。\n\nV1.11 (2021-11)\n修复文档分类文件点击编辑无反应。\n\nV1.10 (2021-10)\n搜索页面增加编辑菜单。\n修复搜索文件跳转文件位置路径错误。\n主页的LinearLayout看不到焦点，增加焦点和点击背景颜色选择器，适配安卓电视遥控器。\n\nV1.9 (2021-08)\n增加搜索页面\n增加文件定位。\n\nV1.8 (2021-06)\n文本编辑器增加查找功能。\n删除文件后定位到文件所在位置。\n目录菜单增加刷新。\n\nV1.7 (2021-03)\n点击文件没有mime赋值*.*，解决文件没有mime点击无响应问题。\n\nV1.6 (2021-02)\n文件属性增加文件大小。\n2.编辑文本文件保存后刷新媒体库更新库里的文件大小。\n\nV1.5 (2021-01)\n文件排序后台保存和读取。\n优化文件时间算法。\n\nV1.4 (2020-12)\n关联主页书签数目和书签页面。\n修复：新建文件没有刷新媒体库，媒体库找不到文件。\n文档分类的TXT、HTML文件列表增加编辑菜单。\n\nV1.3 (2020-07)\n使用(Bitmap)MediaStore.Images.Thumbnails.getThumbnail 的API代替自定义缩略图查询，解决MIUI取不到缩略图的问题。\n文件浏览根目录改为外存目录，修复根目录无权限无法浏览的问题。\n\nV1.2 (2020-06)\n增加书签功能。\n文件夹排前面。\n\nV1.1 (2020-02)\n增加新建文件、文件夹，编辑、保存文件。\n\nV1.0 (2019-05)\n获取文件列表，多种排序，设置显示隐藏文件，图片、视频缩略图。").setPositiveButton("确定", null).show();
                break;
            case 3:
                new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher).setTitle("海天鹰文件管理器 V1.13").setMessage("文件列表，文件属性、分享、重命名、删除，文本编辑。\n作者：海天鹰\nQQ：84429027\n参考：\n文件列表：https://www.jb51.net/article/77589.htm\n文件排序：https://blog.csdn.net/xueyuediana/article/details/80519082\nListView加载Drawable或Bitmap：https://blog.csdn.net/EricFantastic/article/details/48059119\n通过图片路径获取系统图库缩略图：https://binkery.com/archives/401.html").setPositiveButton("确定", null).show();
                break;
            case 4:
                finish();
                break;
        }
        return true;
    }

    public void onClick(View v) {
        //Log.e(Thread.currentThread().getStackTrace()[2] + "", "" + v.getId());
        switch (v.getId()){
            case R.id.layout_rom:
                Intent intent = new Intent(HomeActivity.this, MainActivity.class);
                intent.putExtra("Path", Environment.getExternalStorageDirectory().getPath());
                startActivity(intent);
                break;
            case R.id.linearLayout_video:
                intent = new Intent(HomeActivity.this, CategoryActivity.class);
                intent.putExtra("Category", "Video");
                startActivity(intent);
                break;
            case R.id.linearLayout_audio:
                intent = new Intent(HomeActivity.this, CategoryActivity.class);
                intent.putExtra("Category", "Audio");
                startActivity(intent);
                break;
            case R.id.linearLayout_image:
                intent = new Intent(HomeActivity.this, CategoryActivity.class);
                intent.putExtra("Category", "Image");
                startActivity(intent);
                break;
            case R.id.linearLayout_doc:
                intent = new Intent(HomeActivity.this, CategoryActivity.class);
                intent.putExtra("Category", "Doc");
                startActivity(intent);
                break;
            case R.id.linearLayout_download:
                intent = new Intent(HomeActivity.this, CategoryActivity.class);
                intent.putExtra("Category", "Download");
                startActivity(intent);
                break;
            case R.id.linearLayout_apk:
                intent = new Intent(HomeActivity.this, CategoryActivity.class);
                intent.putExtra("Category", "APK");
                startActivity(intent);
                break;
            case R.id.linearLayout_zip:
                intent = new Intent(HomeActivity.this, CategoryActivity.class);
                intent.putExtra("Category", "ZIP");
                startActivity(intent);
                break;
            case R.id.linearLayout_bookmark:
                intent = new Intent(HomeActivity.this, BookmarksActivity.class);
                startActivity(intent);
                break;
            case R.id.button_micromsg:
                intent = new Intent(HomeActivity.this, MainActivity.class);
                intent.putExtra("Path", Environment.getExternalStorageDirectory().getPath() + File.separator + "tencent" + File.separator + "micromsg" + File.separator + "WeiXin");
                startActivity(intent);
                break;
            case R.id.button_qq:
                intent = new Intent(HomeActivity.this, MainActivity.class);
                intent.putExtra("Path", Environment.getExternalStorageDirectory().getPath() + File.separator + "tencent" + File.separator + "MobileQQ");
                startActivity(intent);
                break;
            case R.id.button_screenshot:
                intent = new Intent(HomeActivity.this, MainActivity.class);
                //String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "DCIM" + File.separator + "Screenshots";
                //String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "Screenshots";
                String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "Screenshots"; //MIUI
                intent.putExtra("Path", path);
                startActivity(intent);
                break;
        }
    }

    void countFile() {
        StatFs stat_rom = new StatFs(Environment.getDataDirectory().getPath()); //  目录：/data
        Log.e(Thread.currentThread().getStackTrace()[2] + "", Environment.getDataDirectory().getPath());
        blockCount = stat_rom.getBlockCount();
        blockSize = stat_rom.getBlockSize();
        availableBlocks = stat_rom.getAvailableBlocks();
        rootInfo = "可用：" + Formatter.formatFileSize(getApplicationContext(), availableBlocks * blockSize) + "，总共：" + Formatter.formatFileSize(getApplicationContext(), blockCount * blockSize);

        Cursor cursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        count_video = cursor.getCount();

        cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        count_audio = cursor.getCount();

        cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        count_image = cursor.getCount();

        cursor = getContentResolver().query(MediaStore.Files.getContentUri("external"), null, MediaStore.Files.FileColumns.MIME_TYPE + "=? or " +  MediaStore.Files.FileColumns.MIME_TYPE + "=? or " +  MediaStore.Files.FileColumns.MIME_TYPE + "=? or " +  MediaStore.Files.FileColumns.MIME_TYPE + "=?", new String[]{ "text/plain", "text/html", "application/msword", "application/pdf" }, null);
        count_doc = cursor.getCount();

        cursor = getContentResolver().query(MediaStore.Files.getContentUri("external"), null, MediaStore.Files.FileColumns.DATA + " like ?", new String[]{ "%" + Environment.getExternalStorageDirectory().getPath() + File.separator + Environment.DIRECTORY_DOWNLOADS + File.separator + "%" }, null);
        count_download = cursor.getCount();

        cursor = getContentResolver().query(MediaStore.Files.getContentUri("external"), null, MediaStore.Files.FileColumns.MIME_TYPE + "=? or " +  MediaStore.Files.FileColumns.MIME_TYPE + "=? or " +  MediaStore.Files.FileColumns.MIME_TYPE + "=?", new String[]{ "application/x-tar", "application/zip", "application/x-gzip" }, null);
        count_zip = cursor.getCount();

        cursor = getContentResolver().query(MediaStore.Files.getContentUri("external"), null, MediaStore.Files.FileColumns.MIME_TYPE + "=?", new String[]{ "application/vnd.android.package-archive" }, null);
        count_apk = cursor.getCount();
        cursor.close();

        String s = Utils.readFile("bookmarks.txt");
        //Log.e(Thread.currentThread().getStackTrace()[2] + "", s);
        String sa[] = s.split("\n");
        count_bookmark = sa.length;
    }

    void updateUI() {
        textView_count_video.setText("" + count_video);
        textView_count_audio.setText("" + count_audio);
        textView_count_image.setText("" + count_image);
        textView_count_doc.setText("" + count_doc);
        textView_count_download.setText("" + count_download);
        textView_count_zip.setText("" + count_zip);
        textView_count_apk.setText("" + count_apk);
        textView_count_bookmark.setText("" + count_bookmark);
        textView_rom.setText(rootInfo);
        progressBar_rom.setProgress((int)((blockCount - availableBlocks) * 100 / blockCount));
    }

    @Override
    public void onResume() {
        super.onResume();
        Thread CF = new Thread() {
            @Override
            public void run() {
                countFile();
                handler.post(runnable);
            }
        };
        new Thread(CF).start();
    }

}